<?php
namespace app\controller;

use app\BaseController;

use app\model\User;  // 引入User模型


use think\facade\Db;

use think\facade\View;
use app\model\UserMsg;

use app\middleware\JWTMiddleware;
use app\middleware\AuthLogin;

use think\Request;


class Auth extends BaseController
{
    public function index() {
        return '成功访问thinkphp接口';
    }

    // 登录
    public function  login(Request $request){
        $input = $request->all();
        $res = UserMsg::where(['username'=>$input['username']])->find();
        if($res  && $res['isDelete'] != 1){
            // 验证密码是否正确
            if (password_verify($input['password'],$res['password'])){
                // 生成Token
                $token = JWTMiddleware::signToken($res['id']);
                // 保存token
                $res = UserMsg::where(['username'=>$input['username']])->update(['token'=>$token]);

                $data = ['msg'=>'登录成功!','access-token'=>$token,'code'=>200];
            }else{
                $data = ['msg'=>'登录失败!密码错误','code'=>403];
            }
        }else{
            $data = ['msg'=>'登录失败!帐号不存在','code'=>403];
        }
        return json($data);
    }
    // 注册
    public function  register(Request $request){
        $input = $request->all();
        // 添加注册时间,标志位
        date_default_timezone_set('PRC');
        $input['registerTime'] = date('Y-m-d h:i:s', time());
        $input['isDelete'] = '0';
        // 密码加密
        $input['password']=password_hash($input['password'],PASSWORD_DEFAULT);

        $res = UserMsg::where(['username'=>$input['username']])->find();
        if(!$res){
            // 不能有相同帐号名
            $res1 = UserMsg::create($input);
            $data = ['msg'=>'注册成功!','code'=>200];
        }else{
            $data = ['msg'=>'注册失败!帐号已存在','code'=>403];
        }
        return json($data);
    }
    // 退出登录
    public function  logout(Request $request){
        // 获取用户id
        $user_id = AuthLogin::getAccessToken($request);

        $res = UserMsg::where(['id'=>$user_id])->update(['token'=>'']);

        return json(['msg'=>'退出登录成功!','code'=>200]);
    }
    // 注销 帐号
    public function  unregister(Request $request){

        // 获取用户id
        $user_id = AuthLogin::getAccessToken($request);

        date_default_timezone_set('PRC');
        $now_date = date('Y-m-d H:i:s',time());

        $res = UserMsg::where(['id'=>$user_id])->update(['token'=>'','isDelete'=>'1','deleteTime'=>$now_date]);

        return json(['msg'=>'注销帐号成功!','code'=>200]);
    }


}
